import { ref ,onMounted} from "vue";
import { getTopCategoryAPI } from "@/apis/category";
import { useRoute } from "vue-router";
import { onBeforeRouteUpdate } from "vue-router";

export function useCategory() {
  // 获取分类数据
const categoryData = ref({});
const route = useRoute();
const getCategory = async (id=route.params.id) => {
  const res = await getTopCategoryAPI(id);
  categoryData.value = res.result;
};
onMounted(() => {
  getCategory();
})

// 监听路由变化时
onBeforeRouteUpdate((to) => {
  //不用route.params.id是 因为 onBeforeRouteUpdate是路由【变化时】 route.params.id是变化后
  //而to 是变化前  to指的是要变化后的路由对象 还没有变化时
  getCategory(to.params.id);
});
  return {
    categoryData,
  };
}
